import 'package:flutter_fitness/app_controller.dart';
import 'package:flutter_fitness/const.dart';
import 'package:flutter_fitness/model/db/record_provider.dart';
import 'package:flutter_fitness/model/db/user_provider.dart';
import 'package:flutter_fitness/model/entity/record.dart';
import 'package:flutter_fitness/pages/login/login_view.dart';
import 'package:flutter_fitness/pages/main/main_view.dart';
import 'package:get/get.dart';
import 'package:shared_preferences/shared_preferences.dart';

class SplashLogic extends GetxController {
  @override
  void onInit() {
    super.onInit();
    SharedPreferences.getInstance().then((pref) async {
      final id = pref.getInt(TAG_LOGIN_ID);
      await Future.delayed(Duration(seconds: 1));
      if (id != null) {
        final provider = UserProvider();
        await provider.open();
        final user = await provider.getUser(id);
        Get.find<AppController>().user.value = user;
        final dateTime = DateTime.now();
        final recordProvide = RecordProvider();
        await recordProvide.open();
        final record = await recordProvide.getRecordByUserIdAndTime(
            user.id, dateTime.year, dateTime.month, dateTime.day);
        if (record == null)
          Get.find<AppController>().record.value = Record(
              userId: id,
              year: dateTime.year,
              month: dateTime.month,
              day: dateTime.day);
        else
          Get.find<AppController>().record.value = record;
        provider.close();
        recordProvide.close();
        Get.off(() => MainPage());
      } else {
        Get.off(() => LoginPage());
      }
    });
  }
}
